/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is Mozilla.org code.
 *
 * The Initial Developer of the Original Code is
 * Mozilla.org.
 * Portions created by the Initial Developer are Copyright (C) 2004
 * the Initial Developer. All Rights Reserved.
 *
 * Author(s): Michael Ryabushkin
 *
 * ***** END LICENSE BLOCK ***** */

/*----------------------
 Contains some of the code is from Mozilla original Cookie Editor
 ----------------------*/


var addflag; //add cookie flag
var addvalues; //add values flag
var curCookie;
var newCookie;

//====================================================================================
function InitEditCookie()
{
	var d = document;
	var wod = window.opener.document;
		
	addflag = (d.location.search.indexOf('addcookie')>0);
	addvalues = (d.location.search.indexOf('addvalues')>0);

	if (!cookieBundle)
    	cookieBundle = document.getElementById("cookieBundle");
	if( !gDateService )
	{
		const nsScriptableDateFormat_CONTRACTID = "@mozilla.org/intl/scriptabledateformat;1";
		const nsIScriptableDateFormat = Components.interfaces.nsIScriptableDateFormat;
		gDateService = Components.classes[nsScriptableDateFormat_CONTRACTID].getService(nsIScriptableDateFormat);
	}

	d.getElementById('ifl_isSecureYes').label=cookieBundle.getString("forSecureOnly");
	d.getElementById('ifl_isSecureNo').label=cookieBundle.getString("forAnyConnection");

	curCookie = new Cookie(
		wod.getElementById('ifl_name').value,
		wod.getElementById('ifl_value').value,
		wod.getElementById('ifl_isDomain').value,
		wod.getElementById('ifl_host').value,
		wod.getElementById('ifl_path').value,
		wod.getElementById('ifl_isSecure').value,
		wod.getElementById('ifl_expires').value,
		wod.getElementById('ifl_expiresOrig').value,
		wod.getElementById('ifl_policy').value );
		
	if (!addflag) {
		if (addvalues) {
			var cn, cc, ch, cp;
			var locStr = document.location.toString();
			var locStrArr = locStr.split("?");
			
			locStr = locStrArr[1];
			locStr = locStr.split("&");
			for(var ii=0; ii<locStr.length; ii++)
			{
				if(locStr[ii].indexOf("=")!=-1)
				{
					var cookieStr = locStr[ii].split("=");
					switch(ii)
					{
					case 1:
						cn = cookieStr[1];
						break;
					case 2:
						cc = cookieStr[1];
						break;
					case 3:
						ch = cookieStr[1];
						break;
					case 4:
						cp = cookieStr[1];
						break;
					}
				}
			}
			d.getElementById("expr_selection").selectedItem	= d.getElementById("expr_session");	
			rebuildDateSelection(d.getElementById("expr_session"));
			curCookie = new Cookie(
					cn,
					cc,
					true,
					ch,
					cp,
					false,
					GetExpireSelection(),
					curCookie.expiresOrig,
					curCookie.policy );
			//var newCookie = curCookie;
		}
		SetFieldProps();	
	
	} else {


		d.getElementById("editCookie").hidden 		= false;	
		d.getElementById("expr_current").hidden 	= true;	
		d.getElementById("ifl_expires").hidden 		= true;	
		d.getElementById("ifl_expires_date").readonly 		= true;	
		d.getElementById("ifl_expires_time").readonly 		= true;	
		
		d.getElementById("ifl_isSecure").hidden 		= true;
	
		d.getElementById('ifl_isSecureChoice').selectedItem=d.getElementById('ifl_isSecureNo');
		
		d.getElementById("expr_selection").selectedItem		= d.getElementById("expr_session");	
		rebuildDateSelection(d.getElementById("expr_session"));
		
		var newdate = (new Date());

		//add a day to the default time, so it does not expire right away.
		newdate = (dateAdd(newdate, "d", 1));		
		
		d.getElementById("ifl_expires_date").value 			= getDateStr(newdate);
		d.getElementById('ifl_expires_time').value  		= getTimeStr(newdate); //newdate.getHours() + ':' + newdate.getMinutes() + ':' +newdate.getSeconds();

		//set date/time picker fields
		FixDate();
		SetDateField();
		FixTime();
		SetTimeField();
		
		
	}

}

//====================================================================================
function Cookie( name,value,isDomain,host,path,isSecure,expires,expiresOrig,policy)
{
  this.name = name;
  this.value = value;
  this.isDomain = (isDomain == cookieBundle.getString("domainColon")?true:false);
  this.host = host;
  this.path = path;
  this.isSecure = (isSecure == cookieBundle.getString("forSecureOnly")?true:false);
  this.expires = expires;
  this.expiresOrig = expiresOrig;
  this.policy = policy;
}
//====================================================================================

//====================================================================================
function SetFieldProps()
{
	var field;
	var i;
	var d = document;

  var props = [
    {id: "ifl_name", value: curCookie.name, readonly: false, hidden: false },
    {id: "ifl_value", value: curCookie.value, readonly: false, hidden: false }, 
    {id: "ifl_isDomain",
     value: curCookie.isDomain?
            cookieBundle.getString("domainColon") : cookieBundle.getString("hostColon"), readonly: false, hidden: false },
    {id: "ifl_host", value: curCookie.host, readonly: false, hidden: false },
    {id: "ifl_path", value: curCookie.path, readonly: false, hidden: false },
    {id: "ifl_isSecure",
     value: curCookie.isSecure ?
            cookieBundle.getString("forSecureOnly") : 
            cookieBundle.getString("forAnyConnection"), readonly: false, hidden: true },
	{id: "ifl_expires", value: curCookie.expires, readonly: false, hidden: false },
	{id: "ifl_expiresOrig", value: curCookie.expires, readonly: false, hidden: true },
	{id: "ifl_expires_date", value: "", readonly: false, hidden: false },
	{id: "ifl_expires_time", value: "", readonly: false, hidden: false }, 
	{id: "ifl_expires_DayOfWeek", value: "", readonly: false, hidden: true }, 
	
  ];


	for(i = 0; i < props.length; i++ ) 
	{
		field 			= d.getElementById(props[i].id);
		field.value 	= props[i].value;
		if (props[i].readonly)
			field.setAttribute("readonly", "true");
		else 
			field.removeAttribute("readonly");
		field.hidden 	= props[i].hidden;
	}

	//select the secure/any connection boxes just in case
	(d.getElementById('ifl_isSecure').value == cookieBundle.getString("forSecureOnly")) ? d.getElementById('ifl_isSecureChoice').selectedItem=d.getElementById('ifl_isSecureYes')  : d.getElementById('ifl_isSecureChoice').selectedItem=d.getElementById('ifl_isSecureNo')

	//rearrange radio bttons if this is a session cookie
	if (curCookie.expires == cookieBundle.getString("AtEndOfSession"))
	{
		d.getElementById("expr_current").hidden 	= true;	
		d.getElementById("ifl_expires").hidden 		= true;	
		d.getElementById("expr_selection").selectedItem		= d.getElementById("expr_session");	
		
		var newdate = (new Date());

		//add a day to the default time, so it does not expire right away.
		newdate = (dateAdd(newdate, "d", 1));		
		
		d.getElementById("ifl_expires_date").value 			= getDateStr(newdate);
		d.getElementById('ifl_expires_time').value  		= getTimeStr(newdate); //newdate.getHours() + ':' + newdate.getMinutes() + ':' +newdate.getSeconds();
		
	}
	else
	{
		d.getElementById("ifl_expires_date").value 			= getDateStr(new Date(d.getElementById("ifl_expires").value))
		d.getElementById('ifl_expires_time').value  		= getTimeStr(new Date(d.getElementById("ifl_expires").value))
	}

	//collapse the new date dialog
	d.getElementById("datetimepickerbox").collapsed = true;

	//set date/time picker fields
	FixDate();
	SetDateField();
	FixTime();
	SetTimeField();

}
//====================================================================================

//------------------------------------------------------------------
function rebuildDateSelection(radio)
{
	if (radio.id == "expr_new") {
		document.getElementById("datetimepickerbox").collapsed = false;
		window.resizeTo(640, 430);
	} else {
		document.getElementById("datetimepickerbox").collapsed = true;
		window.resizeTo(550, 350);
	}
}
//------------------------------------------------------------------


//-----------------------------------------------
function GetExpireSelection()
{
	var sel = document.getElementById('expr_selection').selectedItem.value.toLowerCase();

	switch (sel) 
	{
  	case "expr_current":
  		//alert(curCookie.expires);
  		return curCookie.expires;
  	case "expr_new":
  		//alert(document.getElementById('ifl_expires_date').value + ' ' + document.getElementById('ifl_expires_time').value)
  		return document.getElementById('ifl_expires_date').value + ' ' + document.getElementById('ifl_expires_time').value;
  	case "expr_session":      
    	//alert("session");
  		return "";
  	default:
  		//alert('default:' + curCookie.expires);
  		return curCookie.expires;
  }

	return curCookie.expires;
	
}

//-----------------------------------------------

function test_url(host, path)
{
	var temp;
	
	//check url
	try {
		var ioService = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService);
 		temp = "http://" + host + "/";
 		var newuri = ioService.newURI(temp, null, null);

		try {
			newuri = '';
			temp = '';
 			temp = "http://" + host + "/" + path
 			newuri = ioService.newURI(temp, null, null);
		} catch(e) {
			return 'not a valid path: ' + path;
		}
	
		return 0;
	
	} catch(e) {
		return 'not a valid host: ' + host;
	}

}

//====================================================================================
function createNewCookie()
{

	var name = trim(document.getElementById('ifl_name').value);
	var value = trim(document.getElementById('ifl_value').value);
	var host = trim(document.getElementById('ifl_host').value);
	var path = trim(document.getElementById('ifl_path').value);
	
	var isValidURI = test_url(host, path);
	if ( isValidURI != 0 ) {
		alert('Error: \n' + isValidURI);
		return -1;
	}

	if ( !(name.length > 0) ) {
		alert('Error: \n' + 'please specify name');
		return -1;
	}		
	
	if ( !(value.length > 0) ) {
		alert('Error: \n' + 'please specify value');
		return -1;
	}		

	
	var isDomain = (host.charAt(0) == ".") ? cookieBundle.getString("domainColon") : cookieBundle.getString("hostColon");
	var curCookieIsDomain = curCookie.isDomain ? cookieBundle.getString("domainColon") : cookieBundle.getString("hostColon")


	newCookie = new Cookie(
		name,
		document.getElementById('ifl_value').value,
		isDomain,
		host,
		path,
		((document.getElementById('ifl_isSecureYes').selected == true) ? cookieBundle.getString("forSecureOnly"):cookieBundle.getString("forAnyConnection")),
		GetExpireSelection(),
		curCookie.expiresOrig,
		curCookie.policy );


	return 0;

}
//====================================================================================

//====================================================================================
function SaveCookie()
{
out_d2("Cookie Manager::SaveCookie::BEGIN");		

	var cookieString;
	var wod = window.opener.document;
	var d= document;
	var rc;
	
	rc = createNewCookie();
	if (rc < 0) 
		return false;
	
	if( 
	    (addvalues) || (addflag) || 
//			(curCookie.name != newCookie.name) || 
//			(curCookie.path != newCookie.path) || 
//			(curCookie.host != newCookie.host) || 
			(curCookie.value != newCookie.value) || 
			(curCookie.expires != newCookie.expires) || 
			(curCookie.isSecure != newCookie.isSecure) 	
		)
	{
		var uri = Components.classes["@mozilla.org/network/standard-url;1"].createInstance(Components.interfaces.nsIURI);
		var cservice = Components.classes["@mozilla.org/cookieService;1"].getService().QueryInterface(Components.interfaces.nsICookieService);
//		var cookiemanager = Components.classes["@mozilla.org/cookiemanager;1"].getService(Components.interfaces.nsICookieManager2);
//		cookiemanager.remove( curCookie.host, curCookie.name, curCookie.path, false );

   	//lets specify the uri.spec https if such just in case
   	var HttpProtocol = newCookie.isSecure ? "https://" : "http://"
   	uri.spec = HttpProtocol + newCookie.host + newCookie.path;

out_d2('uri.spec: ' + uri.spec);
   	
		cookieString = '';
		cookieString = cookieString + newCookie.name + "=" + newCookie.value + ";"; 


		if (newCookie.isDomain)
			cookieString = cookieString + "domain=" + newCookie.host +";"

		if (newCookie.expires != "")
			cookieString = cookieString + "expires=" + (new Date(newCookie.expires)) + ";"
	
		cookieString = cookieString + "path=" + newCookie.path + ";"

		if (HttpProtocol == "https://")
			cookieString = cookieString + "secure"

		//alert('cookieString: ' + cookieString);		

		out_d2("Prepared CookieString:\n" + cookieString);
		

		//get the old value
		//var gOldCookieString = cservice.getCookieString(uri, null);

		var rv = cservice.setCookieString(uri, null, cookieString, null );
		//trying to intercept javascript version of NS_FAILED here is useless since
    		//the cookieservice blindly returns NS_OK
    		//from SetCookieString. we have to call GetCookie to see if the cookie was
    		//set correctly...


		var savedIndex = wod.getElementById("cookiesTree").currentIndex;	    
		// reload cookie list in parent
		wod.getElementById('lookupstart').click();
		if (savedIndex != -1)
			wod.getElementById("cookiesTree").treeBoxObject.view.selection.select(savedIndex);
	}

	window.close();
	
out_d2("Cookie Manager::SaveCookie::END");		

	return true;

}
//====================================================================================

//==================================================================================
function SaveAddedCookie()
{
	
}
//==================================================================================